﻿using System;
using System.Windows;
using System.Windows.Input;
using TicTacToe.Core;

namespace _3DTicTacToe.UI
{
    internal partial class NetChatWindow : Window
    {
        private static string _history;

        private readonly Player _remotePlayer;
        private readonly Player _localPlayer;

        public delegate void MessageDelegate(string message);
        public event MessageDelegate MessageReady;

        public void WriteMessage(Player sender, string message)
        {
            historyTextBox.Text += sender.Name + "> " + message + Environment.NewLine;
            _history = historyTextBox.Text;
            historyTextBox.ScrollToEnd();
        }

        public NetChatWindow(Player localPlayer, Player remotePlayer)
        {
            InitializeComponent();

            historyTextBox.Text = _history;
            _remotePlayer = remotePlayer;
            _localPlayer = localPlayer;
        }

        public void ChatMessageReceived(string message)
        {
            Dispatcher.Invoke(new Action<Player, string>(WriteMessage), _remotePlayer, message);
        }

        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            WriteMessage(_localPlayer, chatTextBox.Text);
            if (MessageReady != null) MessageReady(chatTextBox.Text);
            chatTextBox.Text = string.Empty;
        }

        private void chatTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
                sendButton_Click(null, null);
        }
    }
}
